package com.javastar.common.result;

import com.javastar.common.exception.ErrorCode;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.io.Serializable;

/**
 * 统一响应结果
 *
 * @author zxx
 * @date 2023/7/23
 */
@Data
@ApiModel(value = "响应结果")
public class Result<T> implements Serializable {
    private static final long serialVersionUID = 1L;

    /**
     * 响应码
     * <p>
     *     200表示成功，其他值表示失败
     * </p>
     */
    @ApiModelProperty(value = "响应码：200表示成功，其他值表示失败")
    private int code = 200;
    /**
     * 响应消息
     */
    @ApiModelProperty(value = "响应消息")
    private String msg = "success";
    /**
     * 响应数据
     */
    @ApiModelProperty(value = "响应数据")
    private T data;

    public Result() {}

    private  Result(ErrorCode errorCode) {
        this.msg = errorCode.getMsg();
        this.code = errorCode.getCode();
    }

    public Result ok(T data) {
        this.data = data;
        return this;
    }

    public Result error(ErrorCode errorCode) {
        this.msg = errorCode.getMsg();
        this.code = errorCode.getCode();
        return this;
    }

    public Result error(int code, String msg) {
        this.msg = msg;
        this.code = code;
        return this;
    }

    public Result ok() {
        this.code = 200;
        this.msg = "success";
        return this;
    }

    public Result error() {
        this.code = ErrorCode.INTERNAL_SERVER_ERROR.getCode();
        this.msg = ErrorCode.INTERNAL_SERVER_ERROR.getMsg();
        return this;
    }

    public Result data(T data) {
        this.setData(data);
        return this;
    }

    public Result code(ErrorCode errorCode) {
        this.msg = errorCode.getMsg();
        this.code = errorCode.getCode();
        return this;
    }

    public Result code(int code, String msg) {
        this.msg = msg;
        this.code = code;
        return this;
    }
}
